<template>
  <el-dialog title="修改密码" :visible.sync="visible">
    <el-form :model="userForm" :rules="rules" label-width="80px" ref="userDom">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" readonly placeholder="登录名"/>
      </el-form-item>
        <el-form-item label="原密码" prop="password">
          <el-input v-model="userForm.password" show-password placeholder="原密码"/>
        </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="userForm.newPassword" show-password placeholder="新密码"/>
      </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" show-password placeholder="确认密码"/>
        </el-form-item>
      <el-form-item>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" @click="submitInfo">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const initInfo = {
  username: '',
  password: '',
  newPassword: '',
  confirmPassword: ''
}
export default {
  name: 'Password',
  data () {
    return {
      visible: false,
      userForm: {
        ...initInfo
      },
      rules: {
        password: [
          {
            required: true,
            message: '原密码不能为空',
            trigger: 'blur'
          }
        ],
        newPassword: [
          {
            required: true,
            message: '新密码不能为空',
            trigger: 'blur'
          }
        ],
        confirmPassword: [
          {
            required: true,
            message: '确认密码不能为空',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (value !== this.userForm.newPassword) {
                callback(new Error('两次密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      loading: ''
    }
  },
  methods: {
    init (username) {
      /* 开启弹窗 */
      this.visible = true
      this.userForm = { ...initInfo, username }
    },
    submitInfo () {
      this.$refs.userDom.validate(valid => {
        if (valid) {
          this.loading = this.$loading({ text: '加载中...' })
          this.$http.post('/sys/user/password', this.userForm, true).then(data => {
            this.loading.close()
            if (data.code === 0) {
              this.$message({
                message: '修改密码成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('onCloseWin')
                }
              })
            } else {
              this.$alert(data.msg, { type: 'error' })
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
